<template>
  <div class="main">
    <div class="title">
      <div>配置中心</div>
      <el-button type="primary" :icon="CirclePlus" @click="addConfigType"
        >新增广告图片</el-button
      >
    </div>
    <div class="search-bar">
      <div class="label-input">
        <span>自动关机时间：</span>
        <el-input
          v-model="configDataObj['system:device:closeTime'].configValue"
          disabled
          style="width: 200px"
        />
      </div>
      <div class="label-input">
        <span>自动开机时间：</span>
        <el-input
          v-model="configDataObj['system:device:openTime'].configValue"
          disabled
          style="width: 200px"
        />
      </div>
      <div class="label-input">
        <span>用户默认密码：</span>
        <el-input
          v-model="configDataObj['system:password:default'].configValue"
          style="width: 200px"
          @blur="updateConfigData(configDataObj['system:password:default'])"
        />
      </div>
    </div>
    <div class="search-bar">
      <div class="label-input">
        <span>临期提醒天数：</span>
        <el-input
          v-model="configDataObj['expired:reminder:time'].configValue"
          type="number"
          style="width: 200px"
          @blur="updateConfigData(configDataObj['expired:reminder:time'])"
        />
      </div>
      <div class="label-input">
        <span>最大续借天数：</span>
        <el-input
          v-model="configDataObj['renew:book:time'].configValue"
          type="number"
          style="width: 200px"
          @blur="updateConfigData(configDataObj['renew:book:time'])"
        />
      </div>
      <div class="label-input">
        <span>最大借阅期限：</span>
        <el-input
          v-model="configDataObj['borrow:book:time'].configValue"
          type="number"
          style="width: 200px"
          @blur="updateConfigData(configDataObj['borrow:book:time'])"
        />
      </div>
    </div>
    <div class="cut-line"></div>
    <el-table
      :data="tabelData"
      height="400"
      style="width: 100%"
      border
      v-loading="loading"
      :header-cell-style="headerStyle"
    >
      <el-table-column type="index" align="center" label="#" width="50" />
      <el-table-column
        prop="configLabel"
        align="center"
        label="图片播放顺序"
        width="200"
      />
      <el-table-column prop="configValue" align="center" label="图片">
        <template v-slot="scope">
          <img :src="scope.row.configValue" class="table-img" />
        </template>
      </el-table-column>
      <el-table-column prop="remark" align="center" label="备注" width="300" />
      <el-table-column align="center" label="操作" width="200">
        <template v-slot="scope">
          <el-button type="danger" @click="deleteConfig(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!-- 添加弹窗 -->
    <el-dialog v-model="dialogTableVisible" :title="title" width="400">
      <div class="dialog-win">
        <el-form
          ref="ruleFormRef"
          :model="table"
          label-width="auto"
          :rules="rules"
        >
          <el-form-item label="图片播放顺序：" prop="index">
            <el-input
              v-model="table.index"
              type="number"
              style="width: 240px"
            />
          </el-form-item>
          <el-form-item label="图片：" prop="file">
            <el-upload
              ref="upload"
              class="avatar-uploader"
              :multiple="false"
              :show-file-list="false"
              :auto-upload="false"
              :limit="1"
              :on-change="beforeAvatarUpload"
              accept=".jpeg,.png,.jpg"
            >
              <template v-if="table.file">
                <img :src="table.imageUrl" class="avatar" />
                <el-button class="clear" type="danger" @click="clearImg"
                  >清除图片</el-button
                >
              </template>
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
          </el-form-item>
          <el-form-item label="备注：" prop="remark">
            <el-input v-model="table.remark" style="width: 240px" />
          </el-form-item>
          <el-form-item>
            <div class="from-but">
              <el-button type="warning" @click="submit(ruleFormRef)"
                >确定</el-button
              >
              <el-button type="info" @click="resetForm(ruleFormRef)"
                >取消</el-button
              >
            </div>
          </el-form-item>
        </el-form>
      </div>
    </el-dialog>
  </div>
</template>
<script setup>
import { CirclePlus, Plus } from "@element-plus/icons-vue";
import message from "@/util/alert.js";
import { ref, reactive, onBeforeMount, nextTick } from "vue";
import {
  getConfigDataApi,
  updateConfigDataApi,
  getConfigListApi,
  addPictureApi,
  deletePictureApi,
} from "@/api/configApi.js";

const loading = ref(false);
const tabelData = ref([]);
// 配置默认数据
const configDataObj = ref({
  "system:device:closeTime": "",
  "system:device:openTime": "",
  "system:password:default": "",
  "expired:reminder:time": "",
  "renew:book:time": "",
  "borrow:book:time": "",
});
// 表格头部样式
const headerStyle = () => {
  return {
    backgroundColor: "#a0cfff",
    color: "#000000",
    padding: "8px 0px",
  };
};
// 获取默认配置数据
const getconfigData = async () => {
  let res = await getConfigListApi({
    pageNum: 1,
    pageSize: 100,
    type: 0,
  });
  res.data.rows.forEach((element) => {
    configDataObj.value[element.configKey] = element;
  });
};
const updateConfigData = async (configData) => {
  await updateConfigDataApi(configData);
};
// 获取图片配置数据
const getconfigTabelData = async () => {
  loading.value = true;
  let res = await getConfigDataApi({
    configKey: "picture:list:config",
  });
  tabelData.value = res.data;
  loading.value = false;
};
// 添加配置类型
const addConfigType = () => {
  table.value = {
    configKey: "picture:list:config",
    file: "",
    index: "",
    imageUrl: "",
  };
  title.value = "添加图片数据";
  dialogTableVisible.value = true;
  nextTick(() => {
    upload.value.clearFiles();
  });
};
// 弹窗
const table = ref({});
const dialogTableVisible = ref(false);
const title = ref("");
const ruleFormRef = ref(null);
const upload = ref(null);
// 添加、修改的规则
const rules = reactive({
  index: [{ required: true, message: "请输入图片播放顺序", trigger: "blur" }],
  file: [{ required: true, message: "请添加图片", trigger: "change" }],
});
// 超出限制
const clearImg = () => {
  upload.value.clearFiles();
  table.value.file = "";
  table.value.imageUrl = "";
};
// 文件上传前
const beforeAvatarUpload = (rawFile) => {
  console.log(rawFile);
  const fileName = rawFile.name;
  const fileType = fileName.substring(fileName.lastIndexOf("."));
  table.value.file = rawFile.raw;
  let reader = new FileReader();
  reader.readAsDataURL(rawFile.raw);
  reader.onload = () => {
    table.value.imageUrl = reader.result;
  };
  // jpeg,.png,.jpg,.bmp,.gif
  if (fileType === ".jpg" || fileType === ".png" || fileType === ".jpeg") {
    return true;
  } else {
    message.error("不是.jpg.png.jpeg,请上传正确的图片类型");
    return false;
  }
};
// 提交表单
const submit = async (ruleForm) => {
  if (!ruleForm) return;
  await ruleForm.validate(async (valid, fields) => {
    if (valid) {
      const formData = new FormData();
      formData.append("file", table.value.file);
      formData.append("index", table.value.index);
      await addPictureApi(table.value.configKey, formData);
      getconfigTabelData();
      dialogTableVisible.value = false;
      message.success("添加宣传图片成功");
    }
  });
};
// 重置表单
const resetForm = (ruleForm) => {
  ruleForm.resetFields();
  dialogTableVisible.value = false;
  table.value = {};
};
// 删除配置数据
const deleteConfig = (row) => {
  message.confirm({
    title: "提示",
    msg: `是否删除此图片数据`,
    ok: async () => {
      console.log(row)
      await deletePictureApi(row);
      message.success(`删除成功`);
      getconfigTabelData();
    },
  });
};
onBeforeMount(() => {
  getconfigTabelData();
  getconfigData();
});
</script>
    <style lang="scss" scoped>
.main {
  width: 100%;
  height: 100%;
  background-color: #ffffff;
  padding: 10px 20px;
  .title {
    font-size: 20px;
    font-weight: 600;
    display: flex;
    justify-content: space-between;
    span:hover {
      color: #79bbff;
      cursor: pointer;
    }
  }
}
.search-bar {
  margin-top: 20px;
  display: flex;
  align-items: center;
  height: 30px;
  .search-btn {
    background-color: #79bbff;
    color: #ffffff;
  }
  .el-button {
    height: 28px;
  }
}
.label-input {
  display: flex;
  color: #aaaaaa;
  height: 30px;
  align-items: center;
  margin-right: 20px;
  font-weight: 550;
  .el-input {
    border: none;
    height: 30px;
  }
}
.cut-line {
  margin-top: 30px;
  height: 1px;
  background-color: #cdd0d6;
}
.table-img {
  height: 100px;
}
.pagination {
  display: flex;
  justify-content: center;

  .el-pagination {
    margin: auto 0;
    margin-top: 10px;
  }
}
:deep(.el-table) {
  margin-top: 20px;
  .el-table__cell {
    padding: 4px;
  }
  .cell {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
}
.value-list {
  .value-item {
    display: flex;
    flex-direction: row;
    margin-bottom: 10px;
    .el-input {
      margin-right: 10px;
    }
  }
  .add {
    margin-left: 270px;
    margin-bottom: 10px;
    font-size: 24px;
  }
  .add:hover {
    color: #79bbff;
  }
}
.buts {
  width: 100%;
  display: flex;
  justify-content: center;
}
.dialog-win {
  font-size: 16px;
  .avatar-uploader {
    width: 100px;
    height: 100px;
    border: 1px solid;
    text-align: center;
    .avatar-uploader-icon {
      font-size: 40px;
      margin-top: 30px;
    }
    .avatar {
      width: 98px;
      height: 98px;
    }
    .clear {
      margin-left: 5px;
      font-size: 14px;
      padding-left: 5px;
      padding-right: 5px;
      margin-top: 50px;
    }
  }
  .from-but {
    width: 100%;
    display: flex;
    justify-content: right;
  }
}
</style>